package com.ang.juc.n5;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TestBoolean {
    static boolean flag1 = false;
    static volatile boolean flag2 = false;

    public static void main(String[] args) throws InterruptedException {
//        test1();
        test2();
    }

    /**
     * while中添加sleep，及时没有volatile，在cpu空闲的时候会从主内存获取flag1，也会终止
     * @throws InterruptedException
     */
    public static void test1() throws InterruptedException {
        new Thread(() -> {
            while (true) {
                if(flag1){
                    break;
                }
//                try {
//                    Thread.sleep(500);
//                } catch (InterruptedException e) {
//                    throw new RuntimeException(e);
//                }
            }

            System.out.println("终止");
        }).start();

        Thread.sleep(3000);
        flag1 = true;
    }

    public static void test2() throws InterruptedException {
        new Thread(() -> {
            while (true) {
                if(flag2){
                    break;
                }
            }

            System.out.println("终止");
        }).start();

        Thread.sleep(3000);
        flag2 = true;
    }
}
